package servlet;

import bean.Role;
import bean.User;
import dao.JdbcRoleDao;
import dao.JdbcUserDao;
import java.io.IOException;
import java.sql.Date;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.LogFactory;

/**
 * @author yakimovich
 */
public class AddUser extends HttpServlet {

    private RequestDispatcher dispatcher;
    private static org.apache.commons.logging.Log logger 
            = LogFactory.getLog(AddUser.class);

    @Override
    protected void doPost(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {

        if (!(request.getParameter("password")
                .equals(request.getParameter("passwordagain")))) {
            request.setAttribute("error", "passwords not equal");
            dispatcher = getServletContext()
                    .getRequestDispatcher("/newUser.jsp");
            dispatcher.forward(request, response);
            return;
        }

        JdbcUserDao userDao = new JdbcUserDao();

        User user = new User();
        user.setLogin(request.getParameter("login"));
        user.setPassword(request.getParameter("password"));
        user.setEmail(request.getParameter("email"));
        user.setFirstName(request.getParameter("firstname"));
        user.setLastName(request.getParameter("lastname"));
        try {
            user.setBirthday(Date.valueOf(request.getParameter("birth")));
        } catch (IllegalArgumentException e) {
            logger.error(this, e);
            request.setAttribute("error", "Wrong date format");
            dispatcher = getServletContext()
                    .getRequestDispatcher("/newUser.jsp");
            dispatcher.forward(request, response);
        }

        JdbcRoleDao roleDao = new JdbcRoleDao();
        Role roleUser = roleDao.findByName(request.getParameter("role"));
        user.setRole(roleUser);
        try {
            userDao.create(user);
            List<User> list = userDao.findAll();
            request.setAttribute("users", list);
            dispatcher = getServletContext()
                    .getRequestDispatcher("/adminPage.jsp");
            dispatcher.forward(request, response);
        } catch (Exception e) {
            logger.error(this, e);
            request.setAttribute(
                    "error", "User with such login already exists");
            dispatcher = getServletContext()
                    .getRequestDispatcher("/newUser.jsp");
            dispatcher.forward(request, response);
        }
    }
}
